﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using log4net;
using System.Reflection;

[assembly:log4net.Config.XmlConfigurator()]

namespace EncryptDirectory
{
    class Program
    {
        private static readonly ILog _log = log4net.LogManager.GetLogger("Main");

        static int Main(string[] args)
        {
            try
            {
                XElement settings = XElement.Load(
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EncryptDirectorySettings.xml"));

                if (settings.Descendants("Key").Count() != 1)
                    throw new Exception("'Key' node not found in settings file");
                if (settings.Descendants("IV").Count() != 1)
                    throw new Exception("'IV' node not found in settings file");
                if (settings.Descendants("DecryptedDirectory").Count() != 1)
                    throw new Exception("'DecryptedDirectory' node not found in settings file");
                if (settings.Descendants("EncryptedDirectory").Count() != 1)
                    throw new Exception("'EncryptedDirectory' node not found in settings file");

                var key = ASCIIEncoding.UTF8.GetBytes(settings.Descendants("Key").First().Value);
                var iv = ASCIIEncoding.UTF8.GetBytes(settings.Descendants("IV").First().Value);
                var decryptedDirectory = settings.Descendants("DecryptedDirectory").First().Value;
                var encryptedDirectory = settings.Descendants("EncryptedDirectory").First().Value;
                
                _log.Info(string.Format("Decrypted Directory: {0}", decryptedDirectory));
                _log.Info(string.Format("Encrypted Directory: {0}", encryptedDirectory));

                var encryptor = new EncryptionService(key, iv, ".enc");

                if (args.Contains("Decrypt"))
                    encryptor.DecryptDirectory(
                        new DirectoryInfo(encryptedDirectory),
                        new DirectoryInfo(decryptedDirectory));
                else
                    encryptor.EncryptDirectory(
                        new DirectoryInfo(decryptedDirectory),
                        new DirectoryInfo(encryptedDirectory));
            }
            catch (Exception e)
            {
                _log.Error("Error encrypting directory", e);
                return 1;
            }

            return 0;
        }
    }
}
